﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ShoopingWebAPI.Data;
using ShoopingWebAPI.Models;

namespace ShoopingWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CategonryController : ControllerBase
    {
        // 只读字段，用于数据库上下文
        private readonly ShopDbContext _ShopDbContext;

        // 构造函数，注入数据库上下文
        public CategonryController(ShopDbContext shopDbContext)
        {
            _ShopDbContext = shopDbContext;
        }

        // 异步方法，获取所有类别列表
        [HttpGet]
        public async Task<IEnumerable<Category>> GetLiset()
        {
            // 从数据库中异步获取所有类别并返回
            return await _ShopDbContext.Categorys.ToListAsync();
        }

        /// <summary>
        /// 根据ID获取信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("id")]
        public async Task<ActionResult<Category>> Get(int id)
        {
            var category = await _ShopDbContext.Categorys.FindAsync();
            if (category == null)
            {
                return NotFound();
            }
            return category;
        }


        [HttpPost]
        public async Task<ActionResult<int>> Post(Category category)
        {
            _ShopDbContext.AddAsync(category);
             await _ShopDbContext.SaveChangesAsync();
            return category.Id;

        }

        //

        [HttpPut]
        public async Task<IActionResult> Put(Category category)
        {
            var categorylist = await _ShopDbContext.Categorys.FindAsync(category.Id);
            if (categorylist == null)
            {
                return NotFound();
            }
            categorylist.NamMyPropertye = category.NamMyPropertye;
            await _ShopDbContext.SaveChangesAsync();
            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            var categorylist = await _ShopDbContext.Categorys.FindAsync(id);
            if (categorylist==null)
            {
                return NotFound();
            }
            _ShopDbContext.Categorys.Remove(categorylist);
           await _ShopDbContext.SaveChangesAsync();
            return NoContent();
        }
    }
}
